package com.lw.leetcode.dp.c;

import com.lw.test.util.Utils;

import java.util.Arrays;

/**
 * Created with IntelliJ IDEA.
 * 1478. 安排邮筒
 *
 * @author liw
 * @version 1.0
 * @date 2022/10/28 17:25
 */
public class MinDistance {

    public static void main(String[] args) {
        MinDistance test = new MinDistance();

        // 5
//        int[] houses = {1, 4, 8, 10, 20};
//        int k = 3;

        // 9
//        int[] houses = {2, 3, 5, 12, 18};
//        int k = 2;

        // 8
//        int[] houses = {7, 4, 6, 1};
//        int k = 1;

        // 0
//        int[] houses = {3, 6, 14, 10};
//        int k = 4;

        //
        int[] houses = Utils.getArr(100, 1, 10000);
        int k = 65;
        System.out.println(k);
        System.out.println();

        int i = test.minDistance(houses, k);
        System.out.println(i);
    }

    public int minDistance(int[] houses, int k) {
        Arrays.sort(houses);
        int m = houses.length;
        int[][] arr = new int[m][k];
        int l = m * m;
        int[] alls = new int[l];
        for (int i = 0; i < m; i++) {
            for (int j = 0; j < m; j++) {
                alls[i * m + j] = find(houses, i, j);
            }
        }
        for (int i = 1; i < m; i++) {
            int[] itmes = arr[i];
            int end = Math.min(i, k - 1);
            itmes[0] = alls[i];
            for (int j = 1; j <= end; j++) {
                arr[i][j] = arr[i - 1][j - 1];
                for (int t = j - 1; t < i; t++) {
                    int v = arr[t][j - 1] + alls[(t + 1) * m + i];
                    arr[i][j] = Math.min(arr[i][j], v);
                }
            }
        }
        return arr[m - 1][k - 1];
    }

    private int find(int[] houses, int st, int end) {
        int sum = 0;
        int s = houses[st];
        for (int i = st + 1; i <= end; i++) {
            sum += (houses[i] - s);
        }
        int value = sum;
        for (int i = st + 1; i <= end; i++) {
            int c = houses[i] - houses[i - 1];
            sum += (i - st - end + i - 1) * c;
            value = Math.min(value, sum);
        }
        return value;
    }

}
